<template>
  <div class="_wz_echarMap">

    <!--实时数据-->
    <div class="_wz_echarMap_realTime">
      <div class="_wz_echarMap_realTime_top">
        <div style="min-width: 140px;" class="_wz_echarMap_realTime_top_nr">
          <NumberInfo title="车辆实时在线" sub-title="" :sub-total="Math.abs(realTimeData.amplitude)" :status="realTimeData.amplitude > 0 ? 'down' : 'up'" >
            <template #total>
              <CountUp :end="realTimeData.vehicleOnline" :duration="4" style="font-family:'Barlow-Medium1'"/>
            </template>
          </NumberInfo>
        </div>

        <div style="min-width: 110px;" class="_wz_echarMap_realTime_top_nr">
          <NumberInfo title="今日在线数" sub-title="" status="down">
            <template #total>
              <CountUp :end="realTimeData.todayOnline" :duration="4" style="font-family:'Barlow-Medium1'"/>
            </template>
          </NumberInfo>
        </div>

        <div style="min-width: 150px;" class="_wz_echarMap_realTime_top_nr">
          <NumberInfo title="今日行驶里程" sub-title="" status="down">
            <template #total>
              <CountUp :end="realTimeData.drivingToday" :duration="4" style="font-family:'Barlow-Medium1'"/>
            </template>
          </NumberInfo>
        </div>

        <div class="_wz_echarMap_realTime_top_nr">
          <NumberInfo title="今日在线率" sub-title="" status="down">
            <template #total>
              <CountUp :end="realTimeData.todayOnlineRate" :duration="6" :decimals="2" v-font="24" style="font-family:'Barlow-Medium1'"/><span style="color: #0efaee;">%</span>
            </template>
          </NumberInfo>
        </div>

      </div>
    </div>
    <!--地图-->
    <div id="_wz_echarMap"></div>
  </div>
</template>
<script>


import {
  getCurrentInstance,
  inject,
  nextTick,
  reactive,
  toRefs,
  toRef,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  ref,
  defineComponent,
  toRaw,
  watch
} from 'vue'
import {useRouter, useRoute} from "vue-router";
import mapData from "../dynamicVehicle/echartsMap/mapData.js";//包含城市的 中国地图
import chinaMapData from "../dynamicVehicle/echartsMap/chinaMapData.js";//包含省份的 中国地图
import Map from '../3DMap/pageRight.vue'


import {useMainStore} from '../../../store'  //pinia 使用 类似 vuex
import {storeToRefs} from 'pinia'//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex

import * as echartsGL from 'echarts-gl'

//reactive
export default defineComponent({
  name: 'echarMap',//组件名称
  components: {
    Map,
  },//组件引用
  setup(props, context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $echarts = inject('$echarts');//引用echarts
    const $common = inject('$common');//自己封装的方法

    const state = reactive({
      realTimeData:{//实时数据
        vehicleOnline:1357,//车辆实时在线
        amplitude:0,//上涨 下降幅度
        todayOnline:1803,//今日在线
        drivingToday:90150,//今日行驶里程
        todayOnlineRate:(1357 / 5365 * 100).toFixed(2),//今日在线率

      },
      mapMyChart:null,//地图对象
      mapOption:{},//地图属性
      mapSelectData:{},//地图选中的 数据
      chinaDatas:[
        {name:'河北',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'山西',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'辽宁',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'吉林',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'黑龙江',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'江苏',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'浙江',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'安徽',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'福建',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'台湾',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'江西',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'山东',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'河南',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'湖北',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'湖南',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'广东',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'海南',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'四川',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'贵州',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'云南',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'陕西',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'甘肃',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'青海',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'北京',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'天津',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'上海',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'重庆',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'内蒙古',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'广西',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'西藏',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'宁夏',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'新疆',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'香港',value:Math.floor(Math.random() * (100 - 1)) + 1},
        {name:'澳门',value:Math.floor(Math.random() * (100 - 1)) + 1},
      ],

      mapCoordinate:[114.522517,37.291249]

    });


    const loadData = () => {
      setInterval(()=>{
        // state.realTimeData = {//实时数据
        //   vehicleOnline:6000,//车辆实时在线
        //   todayOnline:6000,//今日在线
        //   drivingToday:69658452,//今日行驶里程
        // }


        //今日在线今日在线
        let todayOnline = Number(state.realTimeData.todayOnline) + ($common.randomNum(1,3));
        todayOnline = todayOnline > 3853 ? 3853 : todayOnline;
        state.realTimeData.todayOnline = todayOnline;



        //车辆实时在线
        let vehicleOnline = Number(state.realTimeData.vehicleOnline) + ($common.randomNum(-5,10));
        vehicleOnline = vehicleOnline < 923 ? 923 : (vehicleOnline > todayOnline ? todayOnline : vehicleOnline)

        state.realTimeData.amplitude = state.realTimeData.vehicleOnline - vehicleOnline;//上涨 下降幅度
        state.realTimeData.vehicleOnline = vehicleOnline;



        //今日行驶里程
        let drivingToday = state.realTimeData.drivingToday + vehicleOnline * 0.007;
        state.realTimeData.drivingToday = drivingToday ;


        //今日在线率
        state.realTimeData.todayOnlineRate = Number(todayOnline / 5365 * 100).toFixed(2) ;
      }, 5000)



      let chinaDatas = state.chinaDatas.sort((x,y)=> y.value - x.value) // 正序
      chinaDatas.map((k,i)=>{
        k.type = '车辆数'
        //获取中心点
        k.center = chinaMapData.chinaMapData.features.filter(item => item.properties.name == k.name)[0].properties.cp
      })

      loadMap(chinaDatas);//地图加载
    }


    const loadMap = (data)=>{
      $echarts.registerMap('centerMap', chinaMapData.chinaMapData);
      state.mapMyChart = $echarts.init(document.getElementById('_wz_echarMap'));



      //时间轴
      let year = ["普货运输", "危货运输", "包车客运"]

      //颜色数据
      let colors = ["#1DE9B6", "#1DE9B6", "#FFDB5C", "#FFDB5C", "#04B9FF", "#04B9FF"];


      //地图上的点
      let mapDrop = [];
      // let mapDrop = [
      //   {'name':'山东',value:[117.1582,23.8701,216.66]}
      // ];

      //飞线数据
      let flywireData = []
      // let flywireData = [
      //     [
      //       {coord:[125.8154,44.2584],value:0.07},
      //       {coord:[117.1582,23.8701]},
      //     ]
      // ]


      //柱状图数据
      let rankingData = []
      // let rankingData = [0.07,0.1,0.33,0.38,0.65,0.77,0.77,1.25,1.49,1.93,3.09,6.81,7.78,9.55,11.24,11.57,21.55,26.67,31.41,37.14,40.93,49.03,49.78,53.52,83.31,100.41,156.71,157.17,216.66,237.27]

      //X轴数据
      let rankingName = []
      // let rankingName = ["北京市","辽宁","天津","黑龙江","上海","吉林","内蒙古","海南","山东","青海","江苏","安徽","贵州","甘肃","宁夏","新疆","江西","河南","湖北","福建","浙江","云南","重庆","湖南","河北","陕西","广东","广西","山西","四川"]


      // mapCoordinate
      data.map((k,i)=>{
        //地图上的点
        mapDrop.push( {'name':k.name,value:[k.center[0],k.center[1],k.value]})

        //飞线数据
        flywireData.push( [
          {coord:state.mapCoordinate,value:k.value},
          {coord:k.center},
        ])

        //柱状图数据
        rankingData.push(k.value)

        //柱状图数据
        rankingName.push(k.name)
      })





      let optionXyMap01 = {
        //时间轴
        timeline: {
          orient:'vertical',//竖着
          inverse:true,//是否反向放置
          // rewind:true,//反向播放
          data: year,
          axisType: 'category',//轴的类型 现数据类型 只能使用这个
          autoPlay: true,//自动播放
          playInterval: 3000,//表示播放的速度
          left: 0,
          bottom: 10,
          width: "10%",
          height:300,
          label: {//字体样式
            normal: {
              textStyle: {
                color: '#fff'
              }
            },
            emphasis: {
              textStyle: {
                color: '#fff'
              }
            }
          },
          symbolSize: 10,//[20, 10]  W：20  H:10
          lineStyle: {//轴线
            color: '#fff',//
          },
          // itemStyle: {//文字
          //   color: '#fff',//
          // },
          checkpointStyle: {
            borderColor: '#fff',
            borderWidth: 2
          },
          controlStyle: {
            showNextBtn: true,
            showPrevBtn: true,
            normal: {
              color: '#fff',
              borderColor: '#fff'
            },
            emphasis: {
              color: '#fff',
              borderColor: '#fff'
            }
          },

        },
        baseOption: {
          animation: true,//动画
          animationDuration: 1000,//初始化动画时长
          animationEasing: 'cubicInOut',//初始动画的缓动效果
          animationDurationUpdate: 1000,//数据更新动画的时长
          animationEasingUpdate: 'cubicInOut',//数据更新动画的缓动效果



          grid: {
            right: 10,
            bottom: 30,
            height:260,
            width: "85%"
          },
          //地图数据
          geo: {
            show: true,//显示地图
            map: 'centerMap',//显示什么地图
            roam: true,//
            zoom: 1.2,//大小
            center: [105, 30],
            // center: [113.83531246, 34.0267395887],//中心
            label: {//文本
              emphasis: {//高亮状态下的多边形和标签样式
                show: false,//不显示文字
              }
            },
            itemStyle: {// 图形样式
              normal: {
                borderColor: 'rgba(147, 235, 248, 1)',
                borderWidth: 1,
                areaColor: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.8,
                  colorStops: [{
                    offset: 0,
                    color: 'rgba(147, 235, 248, 0)' // 0% 处的颜色
                  }, {
                    offset: 1,
                    color: 'rgba(147, 235, 248, .2)' // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                },
                shadowColor: 'rgba(128, 217, 248, 1)',
                // shadowColor: 'rgba(255, 255, 255, 1)',
                shadowOffsetX: -2,
                shadowOffsetY: 2,
                shadowBlur: 10
              },
              emphasis: {
                areaColor: '#389BB7',
                borderWidth: 0
              }
            }
          },
        },
        options: [],//地图数据 和 柱状图 数据
      };


      for (var n = 0; n < year.length; n++) {
        optionXyMap01.options.push({

          tooltip: {
            trigger: 'axis', // hover触发器
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
              shadowStyle: {
                color: 'rgba(150,150,150,0.1)' //hover颜色
              }
            }
          },
          yAxis: {
            type: 'value',
            scale: true,
            min: 0,
            boundaryGap: false,
            splitLine: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              margin: 2,
              textStyle: {
                color: '#fff'
              }
            },
          },
          xAxis: {
            // axisLabel: {
            //   show: true,
            //   textStyle: {
            //     color: !!data.xColor ? data.xColor : "#e0e6f1"
            //   }
            // },
            type: 'category',
            // nameGap: 16,//间距
            axisLine: {
              show: true,
              lineStyle: {
                color: '#fff'
              }
            },
            axisTick: {
              show: false,
              lineStyle: {
                color: '#fff'
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#fff'
              }
            },
            data: rankingName
          },
          series: [

            { //地图点的动画效果
              type: 'effectScatter',
              coordinateSystem: 'geo',
              data: mapDrop,
              symbolSize: function(val) {
                return val[2] / 10;
              },
              showEffectOn: 'render',
              rippleEffect: {
                brushType: 'stroke'
              },
              hoverAnimation: true,
              label: {
                normal: {
                  formatter: '{b}',
                  position: 'right',
                  show: true
                }
              },
              itemStyle: {
                normal: {
                  color: colors[n],
                  shadowBlur: 10,
                  shadowColor: colors[n]
                }
              },
              zlevel: 1
            },
            // 地图线的动画效果
            {
              type: 'lines',
              zlevel: 2,
              effect: {
                show: true,
                period: 4, //箭头指向速度，值越小速度越快
                trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
                symbol: 'arrow', //箭头图标
                symbolSize: 3, //图标大小
              },
              lineStyle: {
                normal: {
                  color: colors[n],
                  width: 0.1, //尾迹线条宽度
                  opacity: 0.5, //尾迹线条透明度
                  curveness: .3 //尾迹线条曲直度
                }
              },
              data: flywireData
            },
            //柱状图
            {
              zlevel: 1.5,
              type: 'bar',
              symbol: 'none',
              itemStyle: {
                normal: {
                  color: colors[n]
                }
              },
              data:rankingData,
              barWidth:10,
            }
          ]
        })

      }

      state.mapMyChart.setOption(optionXyMap01, true)




    }


    //窗口改变
    const  windowChanges = ()=>{
      // debugger;
      if(state.mapMyChart != null && state.mapMyChart != "" && state.mapMyChart != undefined){
        toRaw(state.mapMyChart).resize();
      }else{
        nextTick(()=>{
          loadMap();
        })
      }
    };




    // 其他的生命周期
    onBeforeMount(() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted(() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")
      loadData();//页面初始化加载数据


      window.addEventListener('resize', windowChanges, false)
    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate(() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated(() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount(() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted(() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
    }
  }
})


</script>
<style lang="less">
._wz_echarMap {
  position: relative;
  height: 100%;
  overflow: hidden;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  //background: #031b41;

  #_wz_echarMap {
    width: 100%;
    height: 100%;
  }
  ._wz_echarMap_realTime{
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    z-index: 2;
    display: flex;
    justify-content: space-between;

    ._wz_echarMap_realTime_top{
      display: flex;
      ._wz_echarMap_realTime_top_nr{
        margin: 0 20px 0 0;
        .ivu-number-info-total{
          margin-right: 16px;
        }
        .ivu-number-info-title{
          color: #fff;
          margin-bottom: 10px;
          font-size: 16px;
        }
        .ivu-count-up{
          color: #0efaee;
        }
        .ivu-trend-text{
          color: #fff;
        }

        .ivu-trend-colorful.ivu-trend-down .ivu-trend-flag{
          color: #ed4014;
        }
        .ivu-trend-colorful.ivu-trend-up .ivu-trend-flag{
          color: #19be6b;
        }
      }

    }

  }

}
</style>
